const Service = require('egg').Service;
const axios = require('axios');
const crypto = require('crypto');

class SmsService extends Service {
  async sendSms(phone, msg) {
    const {
      app
    } = this;

    // 从配置中获取短信服务相关信息
    const appkey = '5vpfbc'
    const appsecret = '666666'
    const appcode = '1000'


    // 参数校验
    if (!phone) {
      return {
        error: '手机号码不能为空'
      }
    }

    if (!msg) {
      return {
        error: '短信内容不能为空'
      }
    }

    if (msg.length > 1000) {
      return {
        error: '短信内容长度不能超过1000个字'
      }
    }

    // 准备请求参数
    const timestamp = Date.now();
    const sign = this.generateSign(appkey, appsecret, timestamp);

    const requestData = {
      appkey,
      appcode,
      sign,
      phone,
      msg:`【缙云县融媒体中心】${msg}`,
      timestamp,
    };
    console.log('请求参数---------------------------------------------')
    console.log(requestData)

    try {
      // 发送请求到短信接口
      const response = await axios.post(
        'https://msg.zjyxt1.net.cn/sms/batch/v1',
        requestData, {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );
      // 返回接口响应结果
      console.log('返回参数---------------------------------------------')
      console.log(response.data)
      return response.data
    } catch (error) {
      // 处理请求异常
      console.log('异常情况---------------------------------------------')
      console.log(error)
      return {
        error: error.message,
      };
    }
  }

  // 生成签名的辅助方法
  generateSign(appkey, appsecret, timestamp) {
    const signStr = `${appkey}${appsecret}${timestamp}`;
    return crypto.createHash('md5').update(signStr).digest('hex');
  }
}

module.exports = SmsService;